package com.hmall.item.web;

import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {


    @Autowired
    private IItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public PageDTO<Item> list(Integer page, Integer size) {
        //设置当前页与页面大小
        PageDTO<Item> pageDTO = itemService.listPage(page, size);

        return pageDTO;
    }

    /**
     * 修改上架下架状态
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable("id") Long id, @PathVariable("status") Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        if (status==1){
            // 发送MQ消息
            rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,
                    MqConstants.HMALL_INSERT_KEY,
                    item.getId());
        }else {
            rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,
                    MqConstants.HMALL_DELETE_KEY,
                    id);
        }
    }

    /**
     * 添加商品
     *
     * @param item
     */
    @PostMapping
    public void add(@RequestBody Item item) {
        itemService.save(item);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id) {
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 修改商品
     */
    @PutMapping
    public void updata(@RequestBody Item item) {
        itemService.updateById(item);
    }

    /**
     * 根据id删除商品
     */
    @DeleteMapping("{id}")
    public void deleteById(@PathVariable Long id) {
        itemService.removeById(id);
    }

    /**
     * 提交订单 - 扣减库存
     *
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void stock(@PathVariable Long itemId, @PathVariable Integer num) {
        itemService.stock(itemId, num);
    }
}
